import _imports  # 只在此项目有效，其他项目，请去掉此 import
import pybi as pbi
import pandas as pd
from src.data.dataset import load_df

tabs = pbi.add_tabs(["柱状图", "ring图", "折线图"])

with tabs["折线图"]:
    pass
    pbi.add_text("待补充")

with tabs["柱状图"]:
    df = pd.DataFrame(
        {
            "value": [120, 200, 150, 80, 70, 110, 130],
            "week": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
        }
    )
    data = pbi.set_source(df)

    pbi.add_markdown(
        """
# 普通柱状图
参考echarts官方示例，[点击这里查看官网示例](https://echarts.apache.org/examples/zh/editor.html?c=bar-background)
    """
    )

    c = {
        "xAxis": {
            "type": "category",
            "data": pbi.sql(f"select week from {data}").toflatlist(),
        },
        "yAxis": {"type": "value"},
        "series": [
            {
                "data": pbi.sql(f"select value from {data}").toflatlist(),
                "type": "bar",
                "showBackground": True,
                "backgroundStyle": {"color": "rgba(180, 180, 180, 0.2)"},
            }
        ],
    }

    pbi.add_slicer(data["week"]).set_debugTag("week")
    pbi.add_echart(c).set_height("30em")

    # data item style
    #
    pbi.add_markdown(
        """
# 超过一定值，改变图形颜色
参考echarts官方示例，[点击这里查看官网示例](https://echarts.apache.org/examples/zh/editor.html?c=bar-data-color)
    """
    )

    series_data = pbi.sql(f"select value from {data}").js_map(
        """
    return rows.map(v=>{
        if (v.value<=100){
            return {value:v.value,itemStyle:{color:'#a90000'}}
        }
        return v.value
    })
    """
    )

    c = {
        "xAxis": {
            "type": "category",
            "data": pbi.sql(f"select week from {data}"),
        },
        "yAxis": {"type": "value"},
        "series": [
            {
                "data": series_data,
                "type": "bar",
            }
        ],
    }

    pbi.add_echart(c).set_height("30em")

    # 混合图
    # https://echarts.apache.org/examples/zh/editor.html?c=mix-line-bar


with tabs["ring图"]:
    pbi.add_markdown(
        """
# 得分环图
参考echarts官方示例，[点击这里查看官网示例](https://echarts.apache.org/examples/zh/editor.html?c=gauge-ring)
    """
    )

    df_sales = load_df("某咖啡公司销售数据.xlsx")
    df_sales.loc[:, "预计销售成本":"销售额"] = df_sales.loc[:, "预计销售成本":"销售额"].astype(float)
    data_sales = pbi.set_source(df_sales)

    def create_indicators():
        static_dv = pbi.set_source(df_sales[["毛利", "利润额", "销售额"]].sum().to_frame().T)

        dv = pbi.set_dataView(
            f"""
        select round(sum(毛利) *100/(select 毛利 from {static_dv}),1) as value,
            '毛利' as name,"-55%" as titleOffset, "-37%" as detailOffset
        from {data_sales}
        union all
        select round(sum(利润额)*100/(select 利润额 from {static_dv}),1) as value ,
            '利润额' as name ,"-17%" as titleOffset, "0%" as detailOffset
        from {data_sales}
        union all
        select round(sum(销售额)*100/(select 销售额 from {static_dv}),1) as value ,
            '销售额' as name ,"18%" as titleOffset, "35%" as detailOffset
        from {data_sales}
        """
        )

        return dv

    def build_gauge_ring(data_idc):

        data = pbi.sql(f"select * from {data_idc}").js_map(
            """
            return rows.map(r=>{
                return {
                    value:r.value,
                    name:r.name,
                    title: {
                        offsetCenter: ['0%', r.titleOffset]
                    },
                    detail: {
                        valueAnimation: true,
                        offsetCenter: ['0%', r.detailOffset]
                    }
                }
            })
        """
        )

        opts = {
            "series": [
                {
                    "type": "gauge",
                    "startAngle": 90,
                    "endAngle": -270,
                    "pointer": {"show": False},
                    "progress": {
                        "show": True,
                        "overlap": False,
                        "roundCap": True,
                        "clip": False,
                        "itemStyle": {"borderWidth": 1, "borderColor": "#464646"},
                    },
                    "axisLine": {"lineStyle": {"width": 40}},
                    "splitLine": {"show": False, "distance": 0, "length": 10},
                    "axisTick": {"show": False},
                    "axisLabel": {"show": False, "distance": 50},
                    "data": data,
                    "title": {"fontSize": 14},
                    "detail": {
                        "width": 50,
                        "height": 14,
                        "fontSize": 14,
                        "color": "inherit",
                        "borderColor": "inherit",
                        "borderRadius": 20,
                        "borderWidth": 1,
                        "formatter": "{value}%",
                    },
                }
            ]
        }

        return pbi.add_echart(opts).set_height("20em")

    def build_slicers():

        with pbi.box() as b:
            pbi.add_slicer(data_sales["市场类别"])
            pbi.add_slicer(data_sales["区域"])
            pbi.add_slicer(data_sales["产品类别"])

        return b

    idc_dv = create_indicators()

    with pbi.gridBox(
        """
        切片器区域 ring-chart
        切片器区域 table
    """
    ).set_columns_sizes(["auto", 1]):

        build_slicers().set_gridArea("切片器区域")
        build_gauge_ring(idc_dv).set_gridArea("ring-chart")
        pbi.add_table(data_sales).set_gridArea("table")


pbi.to_html("test.html")
